package com.hyacinth.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.OncePerRequestFilter;

import com.hyacinth.common.constant.SysConstant;
import com.hyacinth.core.sysmgr.domain.SysUser;

public class UserSessionFilter extends OncePerRequestFilter {
	
	private String[] ignoreURL = {"/system/index.do","/system/user/login.do","/RES/.*"};//不作过虑的地址
	private String redirectURL = "/system/index.do";

	@SuppressWarnings("unchecked")
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
		//String url = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
		HttpSession session = request.getSession();
		ServletContext application = session.getServletContext();
		Map<String, Object> appMap = null;
		if(!checkRequestURL(request)) {//需要验证的url
			SysUser session_user = (SysUser)session.getAttribute(SysConstant.SYS_SESSION_USER);
			if(null!=session_user) {
				appMap = (HashMap<String, Object>)application.getAttribute(SysConstant.SYS_APPLICATION_USER);
				String session_uuid = (String)session.getAttribute(SysConstant.SYS_SESSION_UUID); //记录session中的uuid
				SysUser application_user = (SysUser)appMap.get(session_uuid);
				if(!session_user.equals(application_user)) {
					session.removeAttribute(SysConstant.SYS_SESSION_USER);
					session.removeAttribute(SysConstant.SYS_SESSION_UUID);
					response.sendRedirect(request.getContextPath().concat(redirectURL));
				}else
					chain.doFilter(request, response);
			}else
				response.sendRedirect(request.getContextPath().concat(redirectURL));
		}
		chain.doFilter(request, response);
	}
	
	/**
	 * 检查当前的URL地址，判断是否在需过滤列表needCheckURLs当中
	 */
	private boolean checkRequestURL(HttpServletRequest request) {
		String url = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
		for(int i=0; i<ignoreURL.length; i++) {
			if(url.matches(ignoreURL[i])) {
				return true; // 如url地址是在不需过滤地址列表中的话，返回true，否则false
			}
		}
		return false;
	}

}
